import { useEffect, useReducer, useState, useRef } from 'react'


const doFetchDataReducer = (state, action) => {
  switch (action.type) {
    case 'INIT':
      return { ...state, isempty: "请输入数据", isLoading: false }
    case 'LOAD':
      return { ...state, isempty: "", isLoading: true }
    case 'SUCCESS':
      return {
        ...state,
        isempty: "",
        isLoading: "",
        data: action.payload,
      }
    case 'FAILURE':
      return { ...state, isempty: "错误了", isLoading: false }
    default:
      throw new Error()
  }
}
console.log({a:[],a:10})
const FetchData = () => {
  const [{ data, isempty, isLoading }, dispatch] = useReducer(
    doFetchDataReducer,
    { isLoading: false, isempty: '请输入数据', data: [] }
  )
  const [search, setSearch] = useState('redux')
  const [url, setUrl] = useState(
    'https://hn.algolia.com/api/v1/search?query=redux'
  )
  const mounted = useRef();
  useEffect(() => {
    if (!mounted.current) {
      mounted.current = true;
      console.log('我挂在了')
    } else {
      dispatch({ type: 'INIT' })
      try {
        dispatch({ type: 'LOAD' })
        setTimeout(() => {
          dispatch({ type: 'SUCCESS', payload: [111, 122] })
        }, 2000);
      } catch (error) {
        dispatch({ type: 'FAILURE' })
      }
    }
  }, [url])

  return (
    <>
      <form
        onSubmit={(e) => {
          setUrl(`https://hn.algolia.com/api/v1/search?query=${search}`)
          e.preventDefault()
        }}
      >
        <input
          type="text"
          value={search}
          onChange={(event) => setSearch(event.target.value)}
        />
        <button type="submit">搜索</button>
      </form>
      {isempty}
      {isLoading ? (
        <div>Loading ...</div>
      ) : (
        <ul>
          {data.map((item, i) => (
            <li key={i}>
              <a href='#'>{item}</a>
            </li>
          ))}
        </ul>
      )}
    </>
  )
}

export default FetchData
